package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"market-distro-sys/cache"
	"market-distro-sys/models"
	"strconv"
	"time"
)

func AppAdd(c *gin.Context) {
	title := c.PostForm("title")
	nation := c.PostForm("nation")
	open := c.PostForm("open")

	data := models.App{

		Title:  title,
		Nation: nation,
		Open:   open,
		Num:    0,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	redis_key := "app_id_" + strconv.Itoa(int(data.ID))
	var app models.App
	models.DB.Where("id = ?", app.ID).First(&app)
	jsonData, _ := json.Marshal(app)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func AppList(c *gin.Context) {
	var app []models.App

	err := models.DB.Find(&app).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "列表查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表查询成功",
		"data": app,
	})
	return
}

func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	var app models.App
	models.DB.Where("id = ?", id).First(&app)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查找成功",
		"data": app,
	})
}

func DownCount(c *gin.Context) {
	id, _ := strconv.Atoi(c.PostForm("id"))
	var app models.App
	err := models.DB.Where("id = ?", id).First(&app).Error
	if err == nil {
		app.Num++
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "下载次数增加",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "下载失败",
		})
	}
}
